<?php
class IssueAction extends CommonAction {
    private $Issue;
	private $Buy;
	private $Wallet;

	public function __construct(){
		parent::__construct();
	    $this->Issue = D('Issue');
		$this->Wallet = D('Wallet');
		$this->Buy = D('Buy');
	}
	//空操作
	Public function _empty(){
	    header("HTTP/1.0 404 Not Found");//使HTTP返回404状态码
	    $this->display("Public:404");
	}
	public function buy(){
        $num = $_POST['num'];
		$code = $_POST['code'];
		$chkcode = strtolower($_SESSION['checkcode']);
		if(!chkNum($num)) $this->error('请输入购买数量！');
		if($code!=$chkcode) $this->error('验证码错误！');

		$mo = new Model();
		$mo->query('set autocommit=0');
		$mo->query('lock tables t_buy write,t_issue write,t_user write');
        $rs=array();

		$u = $mo->table('t_user')->where('id='.$this->auth['id'])->find();
		$issue = $mo->table('t_issue')->where('id='.$_POST['iid'].' and status=0')->find();
		if(!$issue) $this->error('认购活动已结束！');

		if($u['rmb']<$issue['price']*$num) $this->error('余额不够，请充值！');

		$rs[] = $mo->table('t_buy')->add(array(
		    'uid'=>$this->auth['id'],
			'iid'=>$issue['id'],
			'price'=>$issue['price'],
			'num'=>$num,
			'ctime'=>time()
		));

		$rs[] = $mo->table('t_issue')->save(array(
		    'id'=>$issue['id'],
			'deal'=>array('exp','deal+'.$num)
		));

		$rs[] = $mo->table('t_issue')->where('num<=deal')->save(array(
		    'id'=>$issue['id'],
			'status'=>1
		));
 
        $rs[] = $mo->table('t_user')->save(array(
		    'id'=>$this->auth['id'],
			'rmb'=>array('exp','rmb-'.($issue['price']*$num))
		));

		if(chkArr($rs)){
			$mo->query('commit');
			$this->success('认购成功！');
		}else{
			$mo->query('rollback');
			$this->error('认购失败！');
		}
	}
}